package com.augurit.common.dao;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.augurit.common.base.dao.BaseDao;
import com.augurit.common.entity.SysFile;
import com.augurit.common.entity.SysFileLink;
import com.augurit.common.sysfile.convert.SysFileConverter;
import com.augurit.common.sysfile.web.form.SysFileForm;


/**
 * 附件表DAO类
 */
@Repository
public class SysFileDao extends BaseDao<SysFile, Long> {
	
	@Autowired
	private SysFileLinkDao sysFileLinkDao; //关联表DAO类
	
	/**
	 * 根据附件记录主键ID获取附件Form对象
	 * @param id 附件记录主键ID
	 * @return
	 */
	public SysFileForm getForm(Long id){
		SysFileForm form = null;
		if(id != null){
			//转换Form对象
			SysFile entity = this.get(id);
			if(entity != null){
				form = SysFileConverter.convertToForm(entity);
				
				//填充扩展属性
				SysFileLink link = sysFileLinkDao.getBySysFileId(id);
				if(link != null){
					form.setEntity(link.getEntity());
					form.setEntityId(link.getEntityId());
				}
			}
		}
		return form;
	}
	
	/**
	 * 保存附件Form对象
	 * @param form 附件Form对象
	 */
	public void saveForm(SysFileForm form, String userName){
		
		if(form != null){
			SysFile entity = null;
			
			//准备VO对象
			if(form != null && form.getSysFileId() != null){
				
				if(userName != null && userName.trim().length() > 0){
					form.setEemp(userName);
					form.setEdt(new Date());
				}
				
				entity = this.get(form.getSysFileId());
				
				//更新关联表
				sysFileLinkDao.updateEntityInfo(
						entity.getSysFileId(), form.getEntity(), form.getEntityId());
				
				//属性值转换
				SysFileConverter.convert(form, entity);
				
				//保存
				super.save(entity);
				
			}else{
				
				if(userName != null && userName.trim().length() > 0){
					form.setCmp(userName);
					form.setCdt(new Date());
				}
				
				entity = new SysFile();
				
				//属性值转换
				SysFileConverter.convert(form, entity);
				
				//保存
				super.save(entity);
				
				//新建关联表对象
				sysFileLinkDao.add(form.getEntity(), form.getEntityId(), entity.getSysFileId(), null);
			}
			
			//回填ID属性值
			form.setSysFileId(entity.getSysFileId());
		}
	}
}
